<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出"
    :width="dailogWidth"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="dataForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      v-loading="loading"
    >
      <el-form-item label="号码状态" prop="result" label-position="right">
        <el-select v-model="dataForm.result" placeholder="请选择号码状态" style="width: 240px">
          <el-option label="成功" value="success" />
          <el-option label="失败" value="fail" />
          <el-option label="未知" value="unknown" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" v-loading="loading">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { exportGroupApi } from '@/api/equipmentManagement/massTexting.api'
import { formatParams } from "@/utils";
import useToggle from "@/hooks/useToggle";
import useDailogWidth from "@/hooks/useDailogWidth";
const dailogWidth = useDailogWidth("90%", "35%")
const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();
const emit = defineEmits(["refresh"]);
const dataForm = ref({
  result: "",
  id: ""
})
const rules = {
  result: [{ required: true, message: '请选择号码状态', trigger: 'change' },]
}
const handleClose = () => {
  setDialogVisible(false)
}

const handleOpen = (id) => {
  console.log(id)
  setDialogVisible(true)

  nextTick(() => {
    resetForm()
    if(id) {
      dataForm.value.id = id
    }
  })
}

const formRef = ref(null)
const submitForm = async () => {
  setLoading(true)
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      exportGroupApi({ groupId: dataForm.value.id, result: dataForm.value.result }).then(res => {
        console.log(res)
        if(res && res.data && res.data.type === "Buffer") {
          const filename = decodeURIComponent(res.fileName.split("''")[1])
          const decoder = new TextDecoder('utf-8');
          const buffer = new Uint8Array(res.data.data).buffer;
          const str = decoder.decode(buffer);
          const blob = new Blob([str], { type: 'application/octet-stream' });
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = filename || 'default.txt';
          link.click();
          URL.revokeObjectURL(url);
        } else {
          ElMessage({
            message: '暂无可导出数据',
            type: 'warning',
          })
        }
        emit("refresh");
        setLoading(false)
        handleClose()
      }).finally(() => {
        setLoading(false)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

defineExpose({
  handleOpen,
})
</script>
